<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax XHR</title>
    <script src="./ajax.js"></script>
</head>
<body>
    <script>
        // ajax + promise

        /*
            fetch
                url: 请求路径
                options
                    method 请求方法
                    body: 字符串 | FormData
                    headers: JSON,
                    credentials: include,  omit 不支持跨域, 
                    mode: 
                        cors: 服务端必须带有 允许跨域的相应头
                        no-cors: 不带响应头也能跨域
                        same-origin: 必须是域名
                    cache: 
                        default 
                        no-cache 如果已经有缓存, 那么就检查一下缓存是否是最新的, 如果不是最新的会更新本地缓存
                        no-store 不缓存
                        reload 忽略之前的缓存, 缓存本次请求结果
                        force-cache 无论缓存是否过期, 直接读取缓存
        */
       
        var request = function(url, options) {
            let header = {
                'Content-Type': 'application/json; charset=utf-8',
            }
            if (options.headers) {
                options.headers = {
                    ...options.headers,
                    ...header
                }
            }
            options.credentials = 'include';
            options.body = JSON.stringify(options.body);
            if (!options.method) {
                options.method = 'GET'
            }
            return fetch(url, options)
                .then(function(response) {
                    if (response.ok) {
                        var contnet = response.headers.get('Content-Type')
                        console.log(response.headers)
                        if (contnet.includes('application/json')) {
                            return response.json()
                        }
                    } else {
                        throw new Error(response.statusText)
                    }
                })
        }

        // await / async 异步代码, 同步写法
        ;(async function() {
            let login = await request('/login', {
                method: 'POST',
                body: {
                    offset: 10,
                    limit: 150
                }
            })
            console.log('login', login)
            let getOrderList = await request('/getOrderList', {
                method: 'POST',
                body: {
                    offset: 10,
                    limit: 150
                }
            })
            console.log('getOrderList',getOrderList)

        })();


    </script>
</body>
</html>